<template>
  <div class="page-container">
    <div class="page-header">
      <h2 class="page-title">商家管理</h2>
      <el-button @click="refreshMerchants" :loading="loading">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card mb-3">
      <el-form :model="filterForm" inline>
        <el-form-item label="审核状态">
          <el-select v-model="filterForm.status" placeholder="全部状态" clearable>
            <el-option label="待审核" value="PENDING" />
            <el-option label="已通过" value="APPROVED" />
            <el-option label="已拒绝" value="REJECTED" />
          </el-select>
        </el-form-item>
        <el-form-item label="营业状态">
          <el-select v-model="filterForm.isOpen" placeholder="全部" clearable>
            <el-option label="营业中" :value="true" />
            <el-option label="暂停营业" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item label="搜索">
          <el-input v-model="filterForm.keyword" placeholder="输入店铺名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商家列表 -->
    <el-card class="table-card">
      <el-table :data="merchants" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="shopName" label="店铺名称" width="150" />
        <el-table-column prop="ownerName" label="负责人" width="100" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column prop="address" label="地址" show-overflow-tooltip />
        <el-table-column prop="status" label="审核状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isOpen" label="营业状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isOpen ? 'success' : 'warning'">
              {{ scope.row.isOpen ? '营业中' : '暂停' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="申请时间" width="160">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === 'PENDING'" 
              type="success" 
              size="small"
              @click="reviewMerchant(scope.row, 'APPROVED')"
            >
              通过
            </el-button>
            <el-button 
              v-if="scope.row.status === 'PENDING'" 
              type="danger" 
              size="small"
              @click="reviewMerchant(scope.row, 'REJECTED')"
            >
              拒绝
            </el-button>
            <el-button size="small" @click="viewMerchantDetail(scope.row)">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 商家详情弹窗 -->
    <el-dialog v-model="detailVisible" title="商家详情" width="600px">
      <div v-if="selectedMerchant" class="merchant-detail">
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="detail-item">
            <span class="label">店铺名称：</span>
            <span>{{ selectedMerchant.shopName }}</span>
          </div>
          <div class="detail-item">
            <span class="label">负责人：</span>
            <span>{{ selectedMerchant.ownerName }}</span>
          </div>
          <div class="detail-item">
            <span class="label">联系电话：</span>
            <span>{{ selectedMerchant.phone }}</span>
          </div>
          <div class="detail-item">
            <span class="label">地址：</span>
            <span>{{ selectedMerchant.address }}</span>
          </div>
          <div class="detail-item">
            <span class="label">描述：</span>
            <span>{{ selectedMerchant.description || '无' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">审核状态：</span>
            <el-tag :type="getStatusType(selectedMerchant.status)">
              {{ getStatusText(selectedMerchant.status) }}
            </el-tag>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

// 响应式数据
const loading = ref(false)
const merchants = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const detailVisible = ref(false)
const selectedMerchant = ref(null)

const filterForm = reactive({
  status: '',
  isOpen: null,
  keyword: ''
})

// 模拟数据
const mockMerchants = [
  {
    id: 1,
    shopName: '老王炒饭',
    ownerName: '王老板',
    phone: '13800000003',
    address: '校园东门美食街A区1号',
    description: '正宗川菜，口味独特',
    status: 'APPROVED',
    isOpen: true,
    createTime: '2024-02-01 10:00:00'
  },
  {
    id: 2,
    shopName: '刘记面馆',
    ownerName: '刘老板',
    phone: '13800000004',
    address: '校园西门商业街B区2号',
    description: '传统手工面条，汤鲜味美',
    status: 'APPROVED',
    isOpen: true,
    createTime: '2024-02-05 14:30:00'
  },
  {
    id: 3,
    shopName: '新开小店',
    ownerName: '张老板',
    phone: '13800000007',
    address: '校园南门美食街C区3号',
    description: '新开店铺，请多关照',
    status: 'PENDING',
    isOpen: false,
    createTime: '2024-12-20 16:00:00'
  }
]

// 获取商家列表
const getMerchants = async () => {
  try {
    loading.value = true
    
    // 筛选数据
    let filteredMerchants = [...mockMerchants]
    if (filterForm.status) {
      filteredMerchants = filteredMerchants.filter(m => m.status === filterForm.status)
    }
    if (filterForm.isOpen !== null) {
      filteredMerchants = filteredMerchants.filter(m => m.isOpen === filterForm.isOpen)
    }
    if (filterForm.keyword) {
      filteredMerchants = filteredMerchants.filter(m => m.shopName.includes(filterForm.keyword))
    }
    
    total.value = filteredMerchants.length
    const start = (currentPage.value - 1) * pageSize.value
    merchants.value = filteredMerchants.slice(start, start + pageSize.value)
    
  } catch (error) {
    ElMessage.error('获取商家列表失败')
  } finally {
    loading.value = false
  }
}

const refreshMerchants = () => {
  currentPage.value = 1
  getMerchants()
}

const handleSearch = () => {
  currentPage.value = 1
  getMerchants()
}

const handleReset = () => {
  filterForm.status = ''
  filterForm.isOpen = null
  filterForm.keyword = ''
  currentPage.value = 1
  getMerchants()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getMerchants()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  getMerchants()
}

const getStatusType = (status) => {
  const typeMap = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'PENDING': '待审核',
    'APPROVED': '已通过',
    'REJECTED': '已拒绝'
  }
  return textMap[status] || '未知'
}

const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

const reviewMerchant = async (merchant, status) => {
  const action = status === 'APPROVED' ? '通过' : '拒绝'
  try {
    await ElMessageBox.confirm(
      `确认${action}商家 "${merchant.shopName}" 的申请？`,
      `${action}审核`,
      {
        confirmButtonText: `确认${action}`,
        cancelButtonText: '取消',
        type: status === 'APPROVED' ? 'success' : 'warning'
      }
    )
    
    // 模拟审核
    merchant.status = status
    ElMessage.success(`${action}成功`)
    getMerchants()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${action}失败`)
    }
  }
}

const viewMerchantDetail = (merchant) => {
  selectedMerchant.value = merchant
  detailVisible.value = true
}

onMounted(() => {
  getMerchants()
})
</script>

<style scoped>
.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.merchant-detail {
  max-height: 500px;
  overflow-y: auto;
}

.detail-section h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: var(--text-primary);
  border-bottom: 1px solid var(--border-light);
  padding-bottom: 8px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 0;
}

.detail-item .label {
  color: var(--text-regular);
  font-weight: 500;
  min-width: 100px;
}
</style>
